package com.mouseoverstudio.brekee;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.mouseoverstudio.brekee.command.List;

public class Brekee {

	public static void main(String[] args) {
		if (args.length > 0) {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < args.length; i++) {
				sb.append(args[i] + " ");
			}
			exec(sb.toString());
		}
	}

	@SuppressWarnings("unchecked")
	public static void exec(String fullCommand) {
		String[] args = fullCommand.split(" ");
		if (args.length > 0) {
			String commandName = args[0];
			try {
				String commandServiceName = commandName.substring(0, 1)
						.toUpperCase()
						+ commandName.substring(1) + "Service";
				Class service = Class
						.forName("com.mouseoverstudio.brekee.service."
								+ commandServiceName);
				Method method = service.getMethod("serve", String[].class);
				Command command = (Command) method
						.invoke(service, (Object) args);
				BufferedReader read = new BufferedReader(new InputStreamReader(
						bash(command).getInputStream()));
				while (read.ready()) {
					System.out.println(read.readLine());
				}
			} catch (SecurityException e) {
				// e.printStackTrace();
			} catch (NoSuchMethodException e) {
				Logger.error("Command not found: " + commandName);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				Logger.error("Command not found: " + commandName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static Process bash(Command command) throws IOException {
		return command.exec();
	}

	public static List list(String type) {
		return new List(type);
	}

}
